#include "radical_semantic.h"
#include <cmath>
#include <algorithm>

std::map<std::string, SemanticVector> RadicalSemantic::radicalSemantics;
bool RadicalSemantic::initialized = false;

void RadicalSemantic::initialize() {
    if (initialized) return;
    
    // 初始化常用字根的语义向量
    // 这里只是一个示例，实际应用中需要从数据文件加载
    radicalSemantics["一"] = SemanticVector({1.0, 0.0, 0.0, 0.0});  // 数字/单一
    radicalSemantics["二"] = SemanticVector({1.0, 0.5, 0.0, 0.0});  // 数字/双数
    radicalSemantics["人"] = SemanticVector({0.0, 1.0, 0.0, 0.0});  // 人类/人物
    radicalSemantics["亻"] = SemanticVector({0.0, 1.0, 0.0, 0.0});  // 人类/人物（偏旁）
    radicalSemantics["水"] = SemanticVector({0.0, 0.0, 1.0, 0.0});  // 液体/流动
    radicalSemantics["氵"] = SemanticVector({0.0, 0.0, 1.0, 0.0});  // 液体/流动（偏旁）
    radicalSemantics["火"] = SemanticVector({0.0, 0.0, 0.0, 1.0});  // 火焰/热量
    radicalSemantics["灬"] = SemanticVector({0.0, 0.0, 0.0, 1.0});  // 火焰/热量（偏旁）
    
    initialized = true;
}

SemanticVector RadicalSemantic::getSemanticVector(const std::string& radical) {
    if (!initialized) initialize();
    
    auto it = radicalSemantics.find(radical);
    if (it != radicalSemantics.end()) {
        return it->second;
    }
    
    // 如果找不到，返回零向量
    return SemanticVector({0.0, 0.0, 0.0, 0.0});
}

SemanticVector SemanticVector::operator+(const SemanticVector& other) const {
    std::vector<double> result(std::max(values.size(), other.values.size()), 0.0);
    
    for (size_t i = 0; i < values.size(); ++i) {
        result[i] += values[i];
    }
    
    for (size_t i = 0; i < other.values.size(); ++i) {
        result[i] += other.values[i];
    }
    
    return SemanticVector(result);
}

SemanticVector SemanticVector::operator*(double scalar) const {
    std::vector<double> result(values.size());
    for (size_t i = 0; i < values.size(); ++i) {
        result[i] = values[i] * scalar;
    }
    return SemanticVector(result);
}

double SemanticVector::cosineSimilarity(const SemanticVector& other) const {
    double dotProduct = 0.0;
    double normA = 0.0;
    double normB = 0.0;
    
    size_t maxSize = std::max(values.size(), other.values.size());
    for (size_t i = 0; i < maxSize; ++i) {
        double a = (i < values.size()) ? values[i] : 0.0;
        double b = (i < other.values.size()) ? other.values[i] : 0.0;
        
        dotProduct += a * b;
        normA += a * a;
        normB += b * b;
    }
    
    if (normA == 0.0 || normB == 0.0) {
        return 0.0;
    }
    
    return dotProduct / (std::sqrt(normA) * std::sqrt(normB));
}